/*
 * @Author: MrGao
 * @Date: 2023-02-09 16:22:29
 * @LastEditors: MrGao
 * @LastEditTime: 2023-03-05 14:27:30
 * @FilePath: \vue-express\server\app.js
 * @Description:
 *
 *
 */
// const { exec } = require("child_process");
import { exec } from "child_process";
// const express = require("express"),
//   bodyParser = require("body-parser")
import express from "express";
import bodyParser from "body-parser";

const app = express();

// const GitTools = require("./gitTool.js");
import GitTools from "./gitTool.js";
import GitDevlop from "./gitDevlop.js";
// const GitDevlop= require('./gitDevlop');
const gitDevlop = new GitDevlop();
gitDevlop.getCookie();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/versionWardList", async (req, res) => {
  let { version } = req.body;
  try {
    let num = await gitDevlop.getTableList(version);
    let list = await gitDevlop.getDetail(num);
    res.send({
      errorNo: 0,
      list,
    });
  } catch (e) {
    res.send({
      errorNo: 200,
      list: [],
      message: e.message,
    });
  }
});
app.post("/mergeRequest", async (req, res) => {
  console.log("合并开始");

  const { projects, source, target, dir } = req.body;
  try {
    let tasks = [];
    let values = [];
    for (let i = 0; i < projects.length; i++) {
      // let res = await mergeBranch(dir, projects[i], source, target);
      // values.push(res);
      tasks.push(mergeBranch(dir, projects[i], source, target)); //这里是作为分步操作，有待验证
    }
    values = await Promise.all(tasks); //这里是作为分步操作，有待验证
    let success = values
      .filter((item) => item.status == "success")
      .map((item) => item.name);
    let error = values
      .filter((item) => item.status == "error")
      .map((item) => item.name);
    let updated = values
      .filter((item) => item.status == "updated")
      .map((item) => item.name);
    console.log("合并结束");
    res.send({
      errorNo: 0,
      success,
      error,
      updated,
    });
  } catch (e) {
    res.send({
      errorNo: 1,
      data: [],
    });
  }
});
app.post("/updateProject", async (req, res) => {
  const { projects, source, target, dir } = req.body;
  let tasks = [];
  for (let i = 0; i < projects.length; i++) {
    tasks.push(updateProject(dir, projects[i], source, target));
  }
  try {
    await Promise.all(tasks);
    res.send({
      errorNo: 0,
    });
  } catch (e) {
    res.send({
      errorNo: 200,
    });
  }
});
app.post("/updateCommon", async (req, res) => {
  const { projects, source, target, dir } = req.body;
  let tasks = [];
  for (let i = 0; i < projects.length; i++) {
    tasks.push(updateCommon(dir, projects[i], source, target));
  }
  try {
    await Promise.all(tasks);
    res.send({
      errorNo: 0,
    });
  } catch (e) {
    res.send({
      errorNo: 200,
    });
  }
});
app.post("/exitsBranch", async (req, res) => {
  const { projects, branch, dir } = req.body;
  let tasks = [];
  for (let i = 0; i < projects.length; i++) {
    tasks.push(exitsBranch(dir, projects[i], branch));
    tasks.push(exitsBranch(dir, projects[i], branch, true));
  }
  try {
    let result = await Promise.all(tasks);
    console.log("res...", result);
    res.send({
      errorNo: 0,
      res: result,
    });
  } catch (e) {
    console.log("错误", e);
    res.send({
      errorNo: 200,
    });
  }
});
app.post("/exitsMergeMain", async (req, res) => {
  const { projects, branch, dir } = req.body;
  let tasks = [];
  for (let i = 0; i < projects.length; i++) {
    tasks.push(exitsMerge(dir, projects[i]));
  }
  try {
    let result = await Promise.all(tasks);
    res.send({
      errorNo: 0,
      res: result,
    });
  } catch (e) {
    console.log("错误", e);
    res.send({
      errorNo: 200,
    });
  }
});
app.post("/delBranch", async (req, res) => {
  const { projects, branch, dir } = req.body;
  let tasks = [];
  for (let i = 0; i < branch.length; i++) {
    tasks.push(delBranch(dir, projects, branch[i]));
  }
  try {
    let result = await Promise.all(tasks);
    res.send({
      errorNo: 0,
      res: result,
    });
  } catch (e) {
    console.log("错误", e);
    res.send({
      errorNo: 200,
    });
  }
});
app.get("/getBigInt", async (req, res) => {
  let project = `{
    "id": 9007199254740993,
    "name": "123"
  }`;
  res.send(project);
});
app.listen("8082", () => {
  console.log("Server is PORT 8082");
});

async function exitsBranch(dir, project, branch, common = false) {
  const rootDir = dir ? dir : "D:\\wegao\\HIS\\";
  let cwd = rootDir + project;
  let projectName = project;
  if (common) {
    cwd = cwd + "\\src\\common";
    projectName = project + "-common";
  }
  const git = new GitTools(cwd, projectName);
  let res = await git.exitsBranch(branch);
  console.log("结果", res);
  let result = {
    project: projectName,
    res: res === "error" ? false : true,
  };
  return result;
}

async function exitsMerge(dir, project, common = false) {
  const rootDir = dir ? dir : "D:\\wegao\\HIS\\";
  let cwd = rootDir + project;
  let projectName = project;
  if (common) {
    cwd = cwd + "\\src\\common";
    projectName = project + "-common";
  }
  const git = new GitTools(cwd, projectName);
  await git.checkout("main");
  await git.pull("main");
  let res = await git.exitsMerge();
  console.log("结果", res);
  let result = {
    project: projectName,
    res: res.split("\n"),
  };
  return result;
}

async function delBranch(dir, project, branch) {
  const rootDir = dir ? dir : "D:\\wegao\\HIS\\";
  let cwd = rootDir + project;
  let projectName = project;
  // if(common){
  //   cwd=cwd+"\\src\\common"
  //   projectName=project+"-common"
  // }
  const git = new GitTools(cwd, projectName);
  // await git.checkout("main");
  // await git.pull("main");
  let res = await git.delete(branch);
  console.log("结果", res);
  let result = {
    project: projectName,
    res: res.split("\n"),
  };
  return result;
}

async function updateProject(dir, project, source, target) {
  const rootDir = dir ? dir : "D:\\wegao\\HIS\\";
  const git = new GitTools(rootDir + project, project);
  let res = "";
  res = await git.checkout("main");
  res = await git.pull("main");
  return res;
}

async function updateCommon(dir, project, source, target) {
  const rootDir = dir ? dir : "D:\\wegao\\HIS\\";
  const git = new GitTools(rootDir + project + "\\src\\common", "common");
  let res = "";
  res = await git.checkout("main");
  res = await git.pull("main");
  return res;
}

async function mergeBranch(dir, project, source, target) {
  //source--源目录 target--目标目录
  const rootDir = dir ? dir : "D:\\wegao\\HIS\\";
  const git = new GitTools(rootDir + project, project);
  try {
    let res = "";
    res = await git.fetch();
    if (res === "error")
      return {
        name: project,
        status: "error",
      };
    console.log("\x1B[31m%s\x1B[0m", `当前目录${rootDir + project}`);
    console.log("\x1B[31m%s\x1B[0m", `当前分支开始${source}`);
    res = await git.checkout(source);
    if (res === "error")
      return {
        name: project,
        status: "error",
      };
    res = await git.pull(source);
    if (res === "error")
      return {
        name: project,
        status: "error",
      };
    console.log("\x1B[31m%s\x1B[0m", `当前分支${source}`);
    let sourceCommitId = await git.gitLog(source, 1);
    res = await git.checkout(target);
    if (res === "error")
      return {
        name: project,
        status: "error",
      };
    res = await git.fetch();
    if (res === "error")
      return {
        name: project,
        status: "error",
      };
    res = await git.pull(target);
    if (res === "error")
      return {
        name: project,
        status: "error",
      };
    let targetCommitLog = await git.gitLog(target, 2, sourceCommitId.trim());
    if (targetCommitLog.indexOf(target) != -1) {
      console.log(`${project}已更新`);
      return {
        name: project,
        status: "updated",
      };
    }
    console.log("\x1B[31m%s\x1B[0m", `当前分支${target}`);
    res = await git.merge(source);
    if (res === "error")
      return {
        name: project,
        status: "error",
      };
    let isChange = await git.status();
    let diff = await git.diff();
    if (isChange || diff) {
      //如果存在冲突为解决或者未提交的代码需要本地处理
      return {
        name: project,
        status: "error",
      };
    } else {
      res = await git.push(target);
      if (res === "error")
        return {
          name: project,
          status: "error",
        };
    }
    return {
      name: project,
      status: "success",
    };
  } catch (e) {
    console.log("错误,", e);
    return {
      name: project,
      status: "error",
    };
  }
}

function checkBody(type, score) {
  return [checkType(type), checkScore(score)];

  function checkType(type) {
    return ["greater", "less", "equal"].includes(type) ? type : "equal";
  }

  function checkScore(score) {
    const _score = Number(score);
    return isNaN(_score) ? 0 : _score;
  }
}
